<template>
  <div>
    <textarea id="mytextarea"></textarea>
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.show"
      width="403px"
      :before-close="handleClose"
    >
    <!--  -->
      <el-upload
        v-loading="upload.loading"
        :element-loading-text="upload.loadingTxt"
        style="display: inline-block; width: 100%"
        :action="action"
        :accept="upload.fileType"
        :limit="upload.limit"
        :multiple="upload.limit > 1"
        drag
        :data="upload.params"
        :on-exceed="handleExceed"
        :http-request="uploadFile"
        :on-remove="handleRemove"
        :show-file-list="true"
        :file-list="fileList"
        :before-upload="beforeAvatarUpload"
        :auto-upload="true"
        ref="upload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.show = false">取 消</el-button>
        <el-button type="success" @click="submit">上传到服务启</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import load from "./dynamicLoadScript";
export default {
  props: {
    value: {default: ''},
    //插件
    plugins: {
      type: [String, Array],
      default: "link lists image code table wordcounts",
    },
    //工具栏
    toolbar: {
      type: [String, Array],
      default:
        "media  bold italic underline strikethrough | fontsizeselect fontselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink code | removeformat",
    },
    // 菜单栏
    menubar: {
      type: String,
      default: "file edit insert view format table",
    },
    height: {
      type: [Number, String],
      required: false,
      default: 360,
    },
    action: { String, default: "" },
  },
  data() {
    return {
      languageTypeList: {
        en: "en",
        zh: "zh_CN",
        es: "es_MX",
        ja: "ja",
      },
      myValue: "", //当前值
      dialog: {
        show: false,
        title: "选择文件",
      },
      fileList: [],
      upload: {
        loading: false,
        loadingTxt: "上传中...",
        fileType: "*",
        sizeLimit: 1024,
        limit: 1,
        fileList: [], //上传文件列表
        params: {}, // 上传时附带参数
      },
      editor: '',
      callback: null,
      tox: {},
    };
  },
  mounted() {
    this.init();
  },
  watch: {
    value(val) {
      if (this.editor && val!=this.myValue) {
        this.editor.setContent(val||'')
      }
    }
  },
  methods: {
    // 使编辑器的宽度始终为页面的一半
    calcWidth() {
      return document.body.clientWidth / 2 + "px";
    },
    init() {
      // dynamic load tinymce from cdn
      //'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'
      const url =
        "https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js";
      load("/tinymce/tinymce.min.js", (err) => {
        if (err) {
          this.$message.error(err.message);
          return;
        }
        if (window.tinymce) {
          this.initTinymce();
        }
      });
    },
    initTinymce() {
      const _this = this;
      window.tinymce.init({
        selector: `#mytextarea`,
        language: this.languageTypeList["zh"],
        height: this.height,
        body_class: "panel-body ",
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        font_formats:"微软雅黑='微软雅黑';仿宋_GB2312=仿宋_GB2312;宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
        plugins: [
          "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount",
        ],
        end_container_on_empty_block: true,
        powerpaste_word_import: "clean",
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: "square",
        advlist_number_styles: "default",
        // imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],
        media_live_embeds: true, // 媒体实时预览开关
        default_link_target: "_blank",
        link_title: false,
        audio_template_callback: function(data) {
          console.log('autio---'.data);
            return '' + '\n\n' + '';
        },
       nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: (editor) => {
          _this.editor = editor
          if (_this.value) {
            editor.setContent(_this.value);
          }
          let toolbar__group = document.getElementsByClassName(
            "tox-toolbar__group"
          )[0];

          let header = document.getElementsByClassName(
            "tox-mbtn tox-mbtn--select"
          );

          for (let i = 0; i < header.length; i++) {
            header[i].onmouseenter = header[i].onclick = () => {
              setTimeout(() => {
                let menu = document.getElementsByClassName(
                  "tox-collection__group"
                )[0];
                if (menu) {
                  menu.onclick = () => {
                    setTimeout(() => {
                      let label = this.tox.getElementsByClassName(
                        "tox-button tox-button--icon tox-button--naked tox-browse-url"
                      )[0];
                      label.title = "选择文件";
                    }, 300);
                  };
                }
              }, 200);
            };
          }
          toolbar__group.onclick = () => {
            setTimeout(() => {
              let label = this.tox.getElementsByClassName(
                "tox-button tox-button--icon tox-button--naked tox-browse-url"
              )[0];
              label.title = "选择文件";
            }, 300);
          };
          _this.hasInit = true;
          // 值改变时
          editor.on("NodeChange Change KeyUp SetContent", () => {
            this.tox = document.getElementsByClassName(
              "tox tox-silver-sink tox-tinymce-aux"
            )[0];
            _this.myValue = editor.getContent()
            this.$emit("input", editor.getContent());
          });
        },
        setup: (editor) => {
          // 定义按钮，
          /*editor.ui.registry.addButton("mybutton", {
            // 按钮，名
            text: "My button",
            // 图标
            icon: "",
            //点击事件
            onAction: function () {
              // 这里点击后会插入一句话
              editor.insertContent("&nbsp;<b>It's my button!</b>&nbsp;");
            },
          });*/
        },
        // it will try to keep these URLs intact
        // https://www.tiny.cloud/docs-3x/reference/configuration/Configuration3x@convert_urls/
        // https://stackoverflow.com/questions/5196205/disable-tinymce-absolute-to-relative-url-conversions
        convert_urls: false,
        // 整合七牛上传
        // images_dataimg_filter(img) {
        //   setTimeout(() => {
        //     const $image = $(img);
        //     $image.removeAttr('width');
        //     $image.removeAttr('height');
        //     if ($image[0].height && $image[0].width) {
        //       $image.attr('data-wscntype', 'image');
        //       $image.attr('data-wscnh', $image[0].height);
        //       $image.attr('data-wscnw', $image[0].width);
        //       $image.addClass('wscnph');
        //     }
        //   }, 0);
        //   return img
        // },
        images_upload_handler(blobInfo, success, failure, progress) {
          console.log(blobInfo.blob());
          progress(0);
          const formData = new FormData();
          formData.append("file", blobInfo.blob());
          // upload(formData).then(() => {
          success(
            "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2671522424,201163811&fm=26&gp=0.jpg"
          );
          progress(100);
          // })
        },
        file_picker_callback: this.upfile,
        
      });

    },
    upfile(callback, value, meta) {
      // Provide file and text for the link dialog
      if (meta.filetype == "file") {
        this.dialog.show = true;
        this.upload.filetype = "*";
        this.upload.limit = 5;
        this.callback = callback;
        // callback("mypage.html", { text: "My text" });
      }
      // Provide image and alt text for the image dialog
      if (meta.filetype == "image") {
        callback("myimage.jpg", { alt: "My alt text" });
      }
      // Provide alternative source and posted for the media dialog
      if (meta.filetype == "media") {
        //可以在这设置狂傲
        callback("movie.mp4", { source2: "alt.ogg", poster: "image.jpg" });
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.upload.limit}个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeAvatarUpload(file) {
      const fileTypeName = file.name.substring(file.name.lastIndexOf("."));
      const extension =
        this.upload.fileType === "*"
          ? true
          : this.upload.fileType.includes(fileTypeName);
      const isLt2M = file.size / 1024 / 1024 < this.upload.sizeLimit;
      if (!extension) {
        this.$message.error(`只能上传${this.upload.fileType}类型文件`);
        return false;
      }
      if (!isLt2M) {
        this.$message.error(`上传文件大小不能超过 ${this.upload.sizeLimit}MB!`);
      }
      return extension && isLt2M;
    },
    uploadFile(param) {
      this.upload.fileList.push(param.file);
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleClose() {
      this.dialog.show = false;
    },
    submit() {
      this.upload.loading = true;
      let progress = 0;
      let timer = setInterval(() => {
        this.upload.loadingTxt = ++progress;
        if (progress == 100) {
          clearInterval(timer);
          this.upload.loading = false;
          this.dialog.show = false;
          this.clear()
          this.callback("自定义.jpg", { alt: "自定义组件" });
        }
      }, 50);
    },
    //删除上传文件
    handleRemove(file, fileList) {
      let index = -1;
      this.upload.fileList.some((f, i) => {
        if (f.uid == file.uid) {
          index = i;
          return true;
        }
      });
      if (index >= 0) {
        this.upload.fileList.splice(index, 1);
      }
    },
    clear() {
      this.upload.fileList = []
      this.$refs.upload.clearFiles()
    }
  },
};
</script>

<style lang="scss" >
>>> .el-upload {
  width: 100%;
}
.tox {
  z-index: 9999!important;
}
  .tox-statusbar__branding {
    display: none;
  }
</style>